package wangle.com.leletexttovoice;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2017/2/6.
 */

public class OCRUtils {

    private static final String TAG = "OCR";
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String parseImageToString(Bitmap bitmap) throws IOException {
        if( bitmap == null ){
            return "";
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        //图片旋转角度
        int rotate = 0;
        //先获取当前图像的方向，判断是否需要旋转
        //将bitmap转化为input
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        InputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        ExifInterface exif = new ExifInterface(isBm);
        int imageOriention = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        Log.i(TAG, "Current image orientation is " + imageOriention);

        switch (imageOriention){
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
        }

        Log.i(TAG, "Current image rotate is " + rotate);

        //获取当前图片的宽和高
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        //使用Matrix 矩阵对图片进行处理
        Matrix mtx = new Matrix();
        mtx.preRotate(rotate);

        //旋转图片
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
        bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

        //开始调用Tess函数进行识别
        TessBaseAPI baseAPI = new TessBaseAPI();
        baseAPI.setDebug(true);

        //使用默认语言初始化BaseApi
        baseAPI.init(OCRConfig.TESSBASE_PATH, OCRConfig.DEFAULT_LANGUAGE);
        baseAPI.setImage(bitmap);

        // 获取返回值
        String recognizedText = baseAPI.getUTF8Text();
        Log.i(TAG, "exchanged : " + recognizedText);

        return recognizedText;
    }
}
